import { defineStore } from 'pinia'

// 权限接口
interface Permission {
    permissionId: number
    permissionName: string
}

// 角色接口
interface Role {
    roleId: number
    roleName: string
}

// 用户基本信息接口
interface User {
    userId: string
    email: string
    age?: number
    gender?: number
    status?: number
    createTime?: string
}

// 完整用户信息接口
interface UserInfo {
    user: User
    roles: Role[]
    permissions: Permission[]
}

// 扩展Store选项类型以包含persist属性
interface StoreOptions {
    state: () => { userInfo: UserInfo | null };
    actions: {
        setUserInfo(userInfo: UserInfo): void;
        clearUserInfo(): void;
        hasPermission(permissionName: string): boolean;
        isAdmin(): boolean;
        isHotelOwner(): boolean;
    };
    persist?: boolean;
}

export const useUserInfoStore = defineStore('userInfo', {
    state: (): { userInfo: UserInfo | null } => ({
        userInfo: null
    }),
    actions: {
        setUserInfo(userInfo: UserInfo) {
            this.userInfo = userInfo
        },
        clearUserInfo() {
            this.userInfo = null
        },
        // 检查用户是否有特定权限
        hasPermission(permissionName: string): boolean {
            if (!this.userInfo || !this.userInfo.permissions) {
                return false
            }
            
            return this.userInfo.permissions.some(
                (permission: Permission) => permission.permissionName === permissionName
            )
        },
        // 检查是否是管理员
        isAdmin(): boolean {
            return this.hasPermission('admin_manage')
        },
        // 检查是否是酒店商家
        isHotelOwner(): boolean {
            return this.hasPermission('create_hotel')
        }
    },
    persist: true
} as StoreOptions)
